<template>
  <div>
    <!-- 注销用户 -->
    <el-table-form ref="form" :model="query">
      <el-form-item class="merge-item">
        <el-select v-model="qtype" style="width: 170px; margin-right: 2px;">
          <el-option value="csmRgPhone" label="电话" />
          <el-option value="csmCode" label="客户编号" />
          <el-option value="csmName" label="客户名称" />
          <el-option value="csmRgAddress" label="地址" />
          <el-option value="salesmanName" label="销售人员" />
          <el-option value="remark" label="备注" />
          <el-option value="auditor" label="审核人" />
          <el-option value="sfzh" label="身份证号" />
          <el-option value="cardType1" label="使用证" />
          <el-option value="cardType2" label="充值卡" />
          <el-option value="countryName" label="区" />
          <el-option value="streetName" label="街道" />
        </el-select>
        <el-input v-model.trim="txt" placeholder="请输入" clearable @keyup.enter.native="search" />
      </el-form-item>
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select v-model="dateType" style="width: 170px; margin-right: 2px;">
          <el-option label="开户日期" value="createTime" />
          <el-option label="销户日期" value="cancelTime" />
          <el-option label="最后订气时间" value="lastBuyDt" />
        </el-select>
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
        />
      </el-form-item>
      <el-form-item label="所属机构" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
        />
      </el-form-item>
      <el-form-item label="客户类型" prop="csmType">
        <el-select v-model="query.csmType" clearable placeholder="请选择" @change="csmTypeChange">
          <el-option
            v-for="item in customerTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用气性质:" prop="subType">
        <el-select v-model="query.subType" clearable placeholder="请选择">
          <el-option
            v-for="(item,index) in subTypeList"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="csmStatus">
        <el-select v-model="query.csmStatus" disabled clearable placeholder="请选择">
          <el-option
            v-for="item in csmStatusFilterMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户来源" prop="newFrom">
        <el-select v-model="query.newFrom" clearable placeholder="请选择">
          <el-option
            v-for="item in newFromMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否自提" prop="isPickUp">
        <el-select v-model="query.isPickUp" clearable placeholder="请选择">
          <el-option :value="1" label="是" />
          <el-option :value="-1" label="否" />
        </el-select>
      </el-form-item>
      <el-form-item label="结款方式" prop="settlementType">
        <el-select v-model="query.settlementType" clearable placeholder="请选择">
          <el-option :value="1" label="现结" />
          <el-option :value="2" label="月结" />
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="orderBy">
        <el-select v-model="query.orderBy" clearable placeholder="请选择">
          <el-option :value="1" label="按开户日期" />
          <el-option :value="2" label="按积分余额" />
          <el-option :value="3" label="按历史总积分" />
        </el-select>
      </el-form-item>
      <el-form-item label="客户等级" prop="unCheckQuality">
        <el-select v-model="query.unCheckQuality" clearable placeholder="请选择">
          <el-option
            v-for="item in csmLevelMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="[20102,1]" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;">
      <div>
        <!-- <el-button type="primary" icon="el-icon-s-open" @click="batchRecovery">批量恢复</el-button>
        <el-button type="primary" icon="el-icon-delete" @click="batchDelete">批量删除</el-button> -->
        <el-button v-permission="[20102,2]" type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      height="250"
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      :immediate-fetch="false"
      custom-column
      @fetch="fetchData"
    />
    <csm-detail ref="csmDetail" />
    <refillCard ref="refillCard" :card-status-map="accCsmcardCardStatusMap" />
    <occupy ref="occupy" />
    <huiFu ref="huiFu" :hui-fu-fn="huiFuFn" />
    <exportDiglog ref="export" />
  </div>
</template>

<script>
  import { formatColumnMap, parseTime, isWildPhone } from '@/utils'
  import moment from 'dayjs'
  import { querySubTypeMap, csmManageQueryList, customerRecover, customerDelete, customerInfo } from '@/api'
  import CsmDetail from '../../../components/CsmDetailModal/index.vue'
  import RefillCard from './RefillCard'
  import Occupy from './Occupy'
  import { mapGetters } from 'vuex'
  import { minDate } from '@/utils/config'
  import huiFu from './huiFu'

  export default {
    name: 'off-csm-tab',
    components: {
      CsmDetail, RefillCard, Occupy, huiFu, exportDiglog: require('./export.vue').default
    },
    props: {
      csmLerel: {
        type: Number,
        required: true
      },
      treeData: {
        type: Array,
        required: true
      },
      customerTypeMap: {
        type: Array,
        required: true
      },
      subTypeAllList: {
        type: Array,
        required: true
      },
      newFromMap: {
        type: Array,
        required: true
      },
      csmStatusMap: {
        type: Array,
        required: true
      },
      csmLevelMap: {
        type: Array,
        required: true
      },
      csmNewTypeMap: {
        type: Array,
        required: true
      },
      accCsmcardCardStatusMap: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        qtype: 'csmRgPhone',
        dateType: 'createTime',
        txt: '',
        date: [],
        ids: [],
        actionColWidth: 80,
        query: {
          csmType: '',
          csmStatus: -1,
          newFrom: '',
          isPickUp: '',
          settlementType: '',
          orderBy: 1,
          unCheckQuality: '',
          csmRgPhone: '',
          csmId: '',
          subType: ''
        },
        tableData: {
          total: 0,
          data: []
        },
        subTypeList: []
      }
    },
    computed: {
      ...mapGetters([
        'userInfo'
      ]),
      csmStatusFilterMap: function() {
        return this.csmStatusMap.filter(item => item.value === -1)
      },
      column: function() {
        const cols = [
          {
            type: 'index',
            fixed: 'left'
          },
          {
            prop: 'csmCode',
            label: '客户编号',
            width: 105,
            fixed: 'left',
            render: (h, { row }) => <el-link underline={false} onClick={() => this.openCsmDetail(row)}>{row.csmCode}</el-link>
          },
          {
            prop: 'isShare',
            label: '共享状态',
            formatter: row => {
              return row.isShare === 0 ? '非共享' : row.isShare === 1 ? '共享' : ''
            }
          },
          {
            prop: 'csmName',
            label: '客户名称'
          },
          {
            prop: 'csmType',
            label: '客户类型',
            render: (h, { row }) => <span>{ row.csmType && formatColumnMap(this.customerTypeMap, 'value', row.csmType, 'desc') }</span>
          },
          {
            prop: 'subType',
            label: '用气性质',
            width: 110,
            render: (h, { row }) => <span>{ row.subType ? formatColumnMap(this.subTypeAllList, 'value', row.subType, 'label') : ''}</span>
          },
          // {
          //   prop: 'testName',
          //   label: '用户分类'
          // },
          {
            prop: 'openId',
            align: 'center',
            label: '微信用户',
            render: (h, { row }) => row.openId && <svg-icon icon-class='wechat-icon' />
          },
          {
            prop: 'csmQuality',
            label: '客户等级',
            render: (h, { row }) => {
              if (this.csmLerel === 1) return <span>{ row.csmQuality ? formatColumnMap(this.csmLevelMap, 'value', row.csmQuality, 'desc') : '' }</span>
              else {
                if (row.qualityStatus === 2) {
                  return <span>{ row.unCheckQuality ? formatColumnMap(this.csmLevelMap, 'value', row.unCheckQuality, 'desc') : '' }</span>
                } else {
                  return <span style='color: red;'>{ row.unCheckQuality ? formatColumnMap(this.csmLevelMap, 'value', row.unCheckQuality, 'desc') : '' }</span>
                }
              }
            }
          },
          {
            prop: 'csmRgPhone',
            width: 110,
            label: '联系电话'
          },
          {
            prop: 'newType',
            label: '开户类型',
            render: (h, { row }) => <span>{ row.newType ? formatColumnMap(this.csmNewTypeMap, 'value', row.newType, 'desc') : '租用瓶' }</span>
          },
          {
            prop: 'newFrom',
            width: 150,
            label: '客户来源',
            render: (h, { row }) => <span>{ row.newFrom && formatColumnMap(this.newFromMap, 'value', row.newFrom, 'desc') }</span>
          },
          {
            prop: 'deposit',
            align: 'right',
            label: '押金'
          },
          {
            prop: 'csmRgAddress',
            width: 200,
            label: '地址'
          },
          {
            prop: 'nearStationName',
            width: 150,
            label: '所属机构'
          },
          {
            prop: 'cardCount',
            align: 'right',
            label: '充值卡',
            render: (h, { row }) => row.cardCount ? <el-link underline={false} style='margin-right: 0;' onClick={() => this.openRefillCard(row)}>{row.cardCount}</el-link> : <span>{row.cardCount}</span>
          },
          {
            prop: 'lastSCheckDt',
            width: 180,
            label: '最后安检时间',
            render: (h, { row }) => row.lastSCheckDt && (new Date(row.lastSCheckDt).getTime() >= new Date(minDate).getTime()) && <span>{ parseTime(row.lastSCheckDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          // {
          //   prop: 'testName',
          //   width: 150,
          //   label: '隐患等级'
          // },
          {
            prop: 'lastBuyDt',
            width: 180,
            label: '最后订气时间',
            render: (h, { row }) => row.lastBuyDt && (new Date(row.lastBuyDt).getTime() >= new Date(minDate).getTime()) && <span>{ parseTime(row.lastBuyDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'score',
            align: 'right',
            label: '积分'
          },
          {
            prop: 'totalGasCount',
            align: 'right',
            label: '使用瓶数'
          },
          {
            prop: 'isPickUp',
            label: '自提客户',
            render: (h, { row }) => <span>{ row.isPickUp === 1 ? '是' : '否' }</span>
          },
          {
            prop: 'settlementType',
            label: '结款方式',
            render: (h, { row }) => <span>{ row.settlementType === 1 ? '现结' : '月结' }</span>
          },
          {
            prop: 'csmStatus',
            label: '状态',
            render: (h, { row }) => <span>{ row.csmStatus && formatColumnMap(this.csmStatusMap, 'value', row.csmStatus, 'desc') }</span>
          },
          {
            prop: 'createTime',
            width: 110,
            label: '开户日期',
            render: (h, { row }) => <span>{ row.createTime && (new Date(row.createTime).getTime() >= new Date(minDate).getTime()) && parseTime(row.createTime, '{y}-{m}-{d}') }</span>
          },
          {
            prop: 'createUser',
            label: '开户人'
          },
          {
            prop: 'salesmanName',
            label: '销售人员'
          },
          {
            prop: 'cancelTime',
            width: 110,
            label: '销户日期',
            render: (h, { row }) => <span>{ row.cancelTime && (new Date(row.cancelTime).getTime() >= new Date(minDate).getTime()) && parseTime(row.cancelTime, '{y}-{m}-{d}') }</span>
          },
          {
            prop: 'cancelUser',
            label: '销户人'
          },
          {
            prop: 'invalidStr',
            label: '销户原因'
          },
          {
            prop: 'curGasCount',
            align: 'right',
            label: '占用瓶数',
            render: (h, { row }) => row.curGasCount ? <el-link underline={false} style='margin-right: 0;' onClick={() => this.openOccupy(row)}>{row.curGasCount}</el-link> : <span>{row.curGasCount}</span>
          },
          {
            prop: 'remark',
            width: 200,
            label: '备注'
          },
          {
            prop: 'csmOption3',
            label: '售卖方式'
          },
          {
            prop: 'csmOption5',
            label: '安全合同'
          },
          {
            prop: 'auditor',
            label: '审核人'
          },
          {
            prop: 'sfzh',
            width: 200,
            label: '身份证号'
          },
          {
            prop: 'contractNumber',
            label: '合同号'
          },
          // {
          //   prop: 'testName',
          //   label: '使用权费'
          // },
          {
            label: '操作',
            className: 'action-col',
            width: 90,
            align: 'center',
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
                <div>
                  {row.csmStatus === -1 && <el-link v-permission={[20102, 3]} underline={false} size='mini' onClick={() => this.recovery(row, $index)}>
                    恢复
                  </el-link>}
                </div>
              )
            }
          }
          // {
          //   label: '操作',
          //   className: 'action-col',
          //   width: 90,
          //   align: 'center',
          //   fixed: 'right',
          //   render: (h, { row, $index }) => {
          //     return (
          //       <div>
          //         {row.csmStatus === -1 && <el-link v-permission='16' underline={false} size='mini' onClick={() => this.recovery(row, $index)}>
          //           恢复
          //         </el-link>}
          //         {row.csmStatus === -1 && <el-link v-permission='13' underline={false} size='mini' type='danger' onClick={() => this.del(row, $index)}>
          //           删除
          //         </el-link>}
          //       </div>
          //     )
          //   }
          // }  2023.9.14 因为滥用，删除该删除按钮
        ]
        if (this.userInfo.corpCode !== '22016') {
          const csmOption3 = cols.findIndex(item => item.prop === 'csmOption3')
          cols.splice(csmOption3, 1)
          const csmOption5 = cols.findIndex(item => item.prop === 'csmOption5')
          cols.splice(csmOption5, 1)
        }
        return cols
      }
    },
    created() {
    },
    methods: {
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage = 1, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        query[this.qtype] = this.txt
        // 电话号码校验
        if (this.qtype === 'csmRgPhone' && this.txt) {
          if (!isWildPhone(this.txt)) {
            this.$message.error('请输入正确的电话号码!')
            return
          }
          // if (this.txt.length !== 11) {
          //   this.$message.error('请输入正确的电话号码!')
          //   return
          // }
        }
        if (this.qtype === 'cardType1') {
          query.cardType = 1
          query.cardNo = this.txt
          delete query.cardType1
        } else if (this.qtype === 'cardType2') {
          query.cardType = 2
          query.cardNo = this.txt
          delete query.cardType2
        }
        if (this.qtype !== 'cardType1' && this.qtype !== 'cardType2') {
          if (query.cardNo || query.cardNo === '') delete query.cardNo
        }
        if (this.date && this.date.length === 2) {
          query[this.dateType] = moment(this.date[0]).format()
          query[`${this.dateType}End`] = moment(this.date[1]).format()
        }
        let csmQuality = this.query.unCheckQuality
        if (this.customerLerel === 1) {
          query.csmQuality = csmQuality
        } else {
          if (!csmQuality) {
            csmQuality = 0
          }
          query.unCheckQuality = csmQuality
        }
        const res = await csmManageQueryList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      // 打开客户详情弹窗
      async openCsmDetail(row) {
        await this.$refs.csmDetail.open(row)
      },
      del(row, index) {
        // customerDelete
        this.$confirm('确认要删除吗？', '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const code = {
            csmId: row.csmId
          }
          const res = await customerDelete(code)
          if (res.success) {
            this.$refs.lbTable.fetch({ currentPage: 1 })
            this.$message.success('删除成功')
          }
        })
      },
      // 充值卡
      async openRefillCard(row) {
        await this.$refs.refillCard.open(row)
      },
      // 占用瓶
      async openOccupy(row) {
        await this.$refs.occupy.open(row)
      },
      batchRecovery() {},
      batchDelete() {},
      exportFile() {
        const query = {
          ...this._getQuery(this.query)
        }
        query[this.qtype] = this.txt
        if (this.qtype === 'cardType1') {
          query.cardType = 1
          query.cardNo = this.txt
          delete query.cardType1
        } else if (this.qtype === 'cardType2') {
          query.cardType = 2
          query.cardNo = this.txt
          delete query.cardType2
        }
        if (this.qtype !== 'cardType1' && this.qtype !== 'cardType2') {
          if (query.cardNo) delete query.cardNo
        }
        if (this.date && this.date.length === 2) {
          // query[this.dateType] = moment(this.date[0]).format()
          // query[`${this.dateType}End`] = moment(this.date[1]).format()
          query[this.dateType] = this.date[0].toISOString()
          query[`${this.dateType}End`] = this.date[1].toISOString()
        }
        let csmQuality = this.query.unCheckQuality
        if (this.customerLerel === 1) {
          query.csmQuality = csmQuality
        } else {
          if (!csmQuality) {
            csmQuality = 0
          }
          query.unCheckQuality = csmQuality
        }
        if (!this.query.csmStatus) query.csmStatus = 9
        var list = JSON.parse(JSON.stringify(this.column))
        list.pop()
        list.shift()
        const value = {}
        list.forEach(l => {
          value[l.prop] = l.label
          return value
        })
        this.$refs.export.open(query, value)
      },
      async recovery(row) {
        this.$confirm('确认要恢复吗？', '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const params = {
            csmId: row.csmId
          }
          // console.log('row', row)
          const info = await customerInfo({ csmCode: row.csmCode })
          if (info.success && info.data) {
            if (info.data.phoneItems.length > 1) {
              this.$refs.huiFu.open(params, row.csmCode)
            } else {
              this.huiFuFn(params)
            }
          }
          // const res = await customerRecover(code)
          // if (res.success) {
          //   this.$refs.lbTable.fetch({ currentPage: 1 })
          //   this.$message.success('恢复成功')
          // }
        })
      },
      async huiFuFn(params) {
        const res = await customerRecover(params)
        if (res.success) {
          this.$refs.lbTable.fetch({ currentPage: 1 })
          this.$message.success('恢复成功')
        }
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      csmTypeChange(csmType) {
        this.query.subType = ''
        this.subTypeList = []
        this.getSubTypeMap(csmType)
      },
      async getSubTypeMap(csmType) {
        const res = await querySubTypeMap({ csmType })
        this.subTypeList = res.data
      }
    }
  }
</script>

<style scoped>

</style>
